<template>
  <el-form
    ref="formRef"
    style="max-width: 600px"
    :model="form"
    :rules="rules"
    label-width="auto"
    class="form"
    size="default"
  >
    <el-form-item label="姓名" prop="name">
      <el-input v-model="form.name" clearable />
    </el-form-item>
    <el-form-item label="年龄" prop="age">
      <el-input v-model.number="form.age" clearable />
    </el-form-item>
    <el-form-item label="性别" prop="sex">
      <el-radio-group v-model="form.sex">
        <el-radio
          v-for="item in sexList"
          :key="item.value"
          :value="item.value"
          >{{ item.label }}</el-radio
        >
      </el-radio-group>
    </el-form-item>
    <el-form-item label="时间" prop="time">
      <el-date-picker v-model="form.time" type="date" placeholder="请选择" />
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-mention
        v-model="form.email"
        :options="emailOptions"
        whole
        placeholder="请输入"
      />
    </el-form-item>
    <div class="justify-center">
      <el-button @click="reset">重置</el-button>
      <el-button type="success" @click="save">保存</el-button>
    </div>
  </el-form>
</template>
<script setup lang="ts">
import { computed, reactive, ref } from "vue";
const formData = {
  name: null,
  age: null,
  sex: null,
  time: null,
  email: null,
};
const form = reactive({ ...formData });
const formRef = ref();
const sexList = [
  {
    label: "男",
    value: 1,
  },
  {
    label: "女",
    value: 2,
  },
];
const rules = computed(() => {
  return {
    name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
    age: [
      { required: true, message: "请输入年龄" },
      { type: "number", message: "年龄必须是数字" },
    ],
    sex: [{ required: true, message: "请选择性别", trigger: "change" }],
    time: [{ required: true, message: "请选择时间", trigger: "change" }],
    email: [{ required: true, message: "请输入邮箱", trigger: "change" }],
  };
});
const MockData = {
  "@": ["qq.com", "163.com", "gmail.com", "yahoo.com", "outlook.com"],
};
const emailOptions = ref(
  MockData["@"].map((m) => {
    return {
      label: m,
      value: m,
    };
  })
);
function reset() {
  Object.assign(form, formData);
  setTimeout(() => {
    formRef.value.clearValidate();
  }, 0);
}
function save() {
  formRef.value.validate((vaild) => {
    if (!vaild) {
      return;
    }
    console.log("form", form);
  });
}
</script>
<style lang="scss" scoped>
.form {
  width: 100%;
  padding: 20px;
}
.justify-center {
  @include flex(center, flex-start);
}
:deep(.el-input) {
  width: 250px;
}
</style>
